<template>
  <view class="hours-page">
    <!-- 顶部导航栏 -->
    <view class="header">
      <view class="header-content">
        <text class="header-title">工时记录</text>
        <view class="header-right">
          <view class="refresh-btn" @tap="refreshData">
            <text class="refresh-icon">🔄</text>
          </view>
    
        </view>
      </view>
    </view>

    <!-- 月份选择器 -->
    <view class="month-selector">
      <view class="month-item" 
            v-for="(month, index) in monthList" 
            :key="index"
            :class="{ active: selectedMonth === month.value }"
            @tap="selectMonth(month.value)">
        <text class="month-text">{{ month.label }}</text>
      </view>
    </view>

    <!-- 统计信息 -->
    <view class="statistics">
      <view class="stat-item">
        <text class="stat-number">{{ totalProjects }}</text>
        <text class="stat-label">项目总数</text>
      </view>
      <view class="stat-item">
        <text class="stat-number">{{ totalHours }}</text>
        <text class="stat-label">总工时</text>
      </view>
      <view class="stat-item">
        <text class="stat-number">{{ avgHours }}</text>
        <text class="stat-label">平均工时</text>
      </view>
    </view>

    <!-- 工时记录列表 -->
    <view class="hours-list">
      <view class="list-header">
        <text class="list-title">{{ selectedMonthLabel }} 工时记录</text>
      </view>
      
      <view class="hour-item" v-for="(item, index) in filteredHoursList" :key="index">
        <view class="project-info">
          <text class="project-name">{{ item.name }}</text>
          <text class="project-total">总计：{{ item.totalHours }}H</text>
        </view>
        
        <view class="hour-details">
          <view class="detail-item" v-if="item.planningHours > 0">
            <text class="detail-label">前期方案：</text>
            <text class="detail-value">{{ item.planningHours }}H</text>
          </view>
          <view class="detail-item" v-if="item.mechanicalHours > 0">
            <text class="detail-label">机械设计：</text>
            <text class="detail-value">{{ item.mechanicalHours }}H</text>
          </view>
          <view class="detail-item" v-if="item.electricalHours > 0">
            <text class="detail-label">电气设计：</text>
            <text class="detail-value">{{ item.electricalHours }}H</text>
          </view>
        </view>
        
        <view class="record-date">
          <text class="date-text">录入时间：{{ item.recordDate }}</text>
        </view>
      </view>
      
      <!-- 空数据提示 -->
      <view class="empty-data" v-if="filteredHoursList.length === 0">
        <text class="empty-icon">📋</text>
        <text class="empty-text">{{ selectedMonthLabel }} 暂无工时记录</text>
        <text class="empty-tip">请先在主页录入工时信息</text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      selectedMonth: '',
      monthList: [],
      hoursRecords: []
    }
  },
  computed: {
    selectedMonthLabel() {
      const month = this.monthList.find(m => m.value === this.selectedMonth)
      return month ? month.label : ''
    },
    filteredHoursList() {
      return this.hoursRecords.filter(item => {
        if (!this.selectedMonth) return true
        return item.recordMonth === this.selectedMonth && item.totalHours > 0
      })
    },
    totalProjects() {
      return this.filteredHoursList.length
    },
    totalHours() {
      return this.filteredHoursList.reduce((sum, item) => sum + item.totalHours, 0)
    },
    avgHours() {
      if (this.totalProjects === 0) return 0
      return Math.round(this.totalHours / this.totalProjects * 10) / 10
    }
  },
  methods: {
    initMonthList() {
      const currentDate = new Date()
      const currentYear = currentDate.getFullYear()
      const currentMonth = currentDate.getMonth() + 1
      
      this.monthList = []
      for (let i = 0; i < 12; i++) {
        let month = currentMonth - i
        let year = currentYear
        
        if (month <= 0) {
          month += 12
          year -= 1
        }
        
        const monthStr = month < 10 ? `0${month}` : `${month}`
        const value = `${year}-${monthStr}`
        const label = `${year}年${month}月`
        
        this.monthList.push({ value, label })
      }
      
      // 默认选择当前月份
      this.selectedMonth = `${currentYear}-${currentMonth < 10 ? '0' + currentMonth : currentMonth}`
    },
    
    selectMonth(month) {
      this.selectedMonth = month
    },
    
    loadHoursData() {
      try {
        const storedData = uni.getStorageSync('projectHours')
        if (storedData) {
          this.hoursRecords = JSON.parse(storedData)
          console.log('加载工时数据:', this.hoursRecords)
        } else {
          // 如果没有存储数据，初始化为空数组
          this.hoursRecords = []
          console.log('暂无工时数据')
        }
      } catch (e) {
        console.log('读取工时数据失败:', e)
        this.hoursRecords = []
        uni.showToast({
          title: '数据加载失败',
          icon: 'none'
        })
      }
    },
    
    generateMockData() {
      const currentDate = new Date()
      const currentMonth = `${currentDate.getFullYear()}-${(currentDate.getMonth() + 1).toString().padStart(2, '0')}`
      const lastMonth = new Date(currentDate.getFullYear(), currentDate.getMonth() - 1, 1)
      const lastMonthStr = `${lastMonth.getFullYear()}-${(lastMonth.getMonth() + 1).toString().padStart(2, '0')}`
      
      this.hoursRecords = [
        {
          name: 'KZL-YB04-30-湖南长沙湘油泵',
          totalHours: 24,
          planningHours: 8,
          mechanicalHours: 10,
          electricalHours: 6,
          recordMonth: currentMonth,
          recordDate: `${currentDate.getFullYear()}-${(currentDate.getMonth() + 1).toString().padStart(2, '0')}-${currentDate.getDate().toString().padStart(2, '0')}`
        },
        {
          name: 'KZL-YB07-15-广东深圳华为技术',
          totalHours: 36,
          planningHours: 12,
          mechanicalHours: 15,
          electricalHours: 9,
          recordMonth: currentMonth,
          recordDate: `${currentDate.getFullYear()}-${(currentDate.getMonth() + 1).toString().padStart(2, '0')}-${(currentDate.getDate() - 1).toString().padStart(2, '0')}`
        },
        {
          name: 'KZL-YB08-23-浙江杭州阿里巴巴',
          totalHours: 18,
          planningHours: 6,
          mechanicalHours: 8,
          electricalHours: 4,
          recordMonth: lastMonthStr,
          recordDate: `${lastMonth.getFullYear()}-${(lastMonth.getMonth() + 1).toString().padStart(2, '0')}-28`
        }
      ]
    },
 
    
    refreshData() {
      this.loadHoursData()
      uni.showToast({
        title: '数据已刷新',
        icon: 'success',
        duration: 1500
      })
    }
  },
  
  onLoad() {
    this.initMonthList()
    this.loadHoursData()
  },
  
  onShow() {
    // 页面显示时刷新数据，以防从主页录入新数据后返回
    this.loadHoursData()
  }
}
</script>

<style lang="scss">
.hours-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

/* 顶部导航栏 */
.header {
  background: linear-gradient(135deg, #4169E1, #6A5ACD);
  padding: 20rpx 30rpx;
  padding-top: 60rpx;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  color: white;
  font-size: 36rpx;
  font-weight: bold;
}

.refresh-btn {
  width: 50rpx;
  height: 50rpx;
  background-color: rgba(255, 255, 255, 0.3);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20rpx;
}

.refresh-icon {
  color: white;
  font-size: 24rpx;
}

.back-btn {
  color: white;
  font-size: 28rpx;
  padding: 10rpx 20rpx;
  border: 1rpx solid rgba(255, 255, 255, 0.5);
  border-radius: 20rpx;
}

/* 月份选择器 */
.month-selector {
  display: flex;
  padding: 20rpx 30rpx;
  background-color: white;
  margin: 20rpx 30rpx;
  border-radius: 15rpx;
  overflow-x: auto;
  white-space: nowrap;
}

.month-item {
  display: inline-block;
  padding: 15rpx 25rpx;
  margin-right: 20rpx;
  border-radius: 25rpx;
  background-color: #f8f8f8;
  border: 1rpx solid #e0e0e0;
  flex-shrink: 0;
}

.month-item.active {
  background-color: #4169E1;
  border-color: #4169E1;
}

.month-text {
  font-size: 26rpx;
  color: #666;
}

.month-item.active .month-text {
  color: white;
}

/* 统计信息 */
.statistics {
  display: flex;
  background-color: white;
  margin: 0 30rpx 20rpx;
  border-radius: 15rpx;
  padding: 30rpx 0;
}

.stat-item {
  flex: 1;
  text-align: center;
  position: relative;
}

.stat-item:not(:last-child):after {
  content: '';
  position: absolute;
  right: 0;
  top: 20%;
  height: 60%;
  width: 1rpx;
  background-color: #e0e0e0;
}

.stat-number {
  display: block;
  font-size: 48rpx;
  font-weight: bold;
  color: #4169E1;
  margin-bottom: 10rpx;
}

.stat-label {
  font-size: 24rpx;
  color: #999;
}

/* 工时记录列表 */
.hours-list {
  background-color: white;
  margin: 0 30rpx;
  border-radius: 15rpx;
  overflow: hidden;
}

.list-header {
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
  background-color: #fafafa;
}

.list-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.hour-item {
  padding: 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.hour-item:last-child {
  border-bottom: none;
}

.project-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.project-name {
  font-size: 30rpx;
  color: #333;
  font-weight: 500;
  flex: 1;
}

.project-total {
  font-size: 28rpx;
  color: #4169E1;
  font-weight: bold;
  background-color: #E6F0FF;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
}

.hour-details {
  margin-bottom: 15rpx;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8rpx;
}

.detail-label {
  font-size: 26rpx;
  color: #666;
}

.detail-value {
  font-size: 26rpx;
  color: #333;
  font-weight: 500;
}

.record-date {
  text-align: right;
}

.date-text {
  font-size: 24rpx;
  color: #999;
}

/* 空数据提示 */
.empty-data {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 80rpx 30rpx;
}

.empty-icon {
  font-size: 80rpx;
  margin-bottom: 20rpx;
}

.empty-text {
  font-size: 32rpx;
  color: #999;
  margin-bottom: 15rpx;
}

.empty-tip {
  font-size: 26rpx;
  color: #ccc;
}

/* 响应式处理 */
@media screen and (min-width: 500px) {
  .month-selector {
    justify-content: center;
  }
  
  .month-item {
    margin: 0 10rpx;
  }
}
</style>
